package exp7;


import java.util.HashSet;
import java.util.Random;

/**
 * Function:
 * Editor: HexWarrior6
 * Date: 2023/12/7 19:16
 */
public class Students {
    static final int MAXN = (int) 1e4;
    int aveScore;
    String stuNumber;

    public Students(int aveScore, String stuNumber) {
        this.aveScore = aveScore;
        this.stuNumber = stuNumber;
    }

    @Override
    public String toString() {
        return "aveScore=" + aveScore + " stuNumber=" + stuNumber;
    }

    public static Students[] bucketSort(Students[] stu) {
        Students max = stu[0];
        for (int i = 0; i < stu.length; i++) {
            if (stu[i] == null) {
                break;
            }
            if (stu[i].aveScore > max.aveScore) {
                max = stu[i];
            }
        }

        Students[][] bucketArray = new Students[max.aveScore + 1][MAXN];
        for (int i = 0; i < stu.length; i++) {
            if (stu[i] == null) {
                continue; // 跳过null元素
            }
            int j;
            for (j = 0; j < MAXN; j++) {
                if (bucketArray[stu[i].aveScore][j] == null) {
                    break;
                }
            }
            bucketArray[stu[i].aveScore][j] = stu[i];
        }

        Students[] ans = new Students[stu.length];
        int index = 0;
        for (int i = 0; i <= max.aveScore; i++) {
            for (int j = 0; j < MAXN; j++) {
                if (bucketArray[i][j] == null) {
                    break;
                }
                ans[index++] = bucketArray[i][j];
            }
        }
        return ans;
    }


    public static void main(String[] args) {
        final int N = (int) 10;
        Students[] arr = new Students[N];
        Random rand = new Random();
        HashSet<Integer> flag = new HashSet<>();
        for (int i = 0; i < N; i++) {
            int n = rand.nextInt(100);
            if (flag.contains(n)) {
                i--;
            } else {
                arr[i] = new Students(rand.nextInt(60) + 40, "s" + (n + 1000));
                flag.add(n);
            }
        }
        Students[] ans = bucketSort(arr);
        System.out.println("before sort:");
        for (Students each : arr) {
            System.out.println(each);
        }
        System.out.println("after sort:");
        for (Students each : ans) {
            System.out.println(each);
        }
    }
}